﻿using System;
using System.Collections.Generic;
using MF.Networker;
using System.Threading;

namespace Game.Foundation
{
    /// <summary>
    /// 一个Dispatcher实例会对应一个分发处理线程，因此，实例越多越可能造成锁竞争等问题
    /// </summary>
    /// <typeparam name="T">分发处理消息的具体类型，多为二进制协议，可执行命令对象等</typeparam>
    public abstract class AbsDispatcher<T> : IProducer<T>
    {
        private static ConcurrentQueue<T> queue = new ConcurrentQueue<T>();

        /// <summary>
        /// 内部处理消息的循环
        /// </summary>
        public void Loop()
        {
            ThreadPool.QueueUserWorkItem(state =>
            {
                while (true)
                {
                    try
                    {
                        T item = queue.Consume();
                        this.Handle(item);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                        Console.WriteLine(e.StackTrace);
                    }
                }
            });
        }

        /// <summary>
        /// 由子类实现的消息处理逻辑
        /// </summary>
        /// <param name="item"></param>
        protected abstract void Handle(T item);

        #region IProducer<T> 成员

        public void Produce(T item)
        {
            queue.Produce(item);
        }

        #endregion
    }
}
